package br.com.statizo.financeiro.config;

import java.io.IOException;
import java.util.Properties;


public class DatabaseConfigurator {

	private Properties props;

	private static final String URL_PROPERTY_NAME = "jdbc.connection.url.property.name";
	private static final String JDBC_PATH = "/META-INF/jdbc.properties";
	private static final String JDBC_URL_REPLACE_PROPERTY = "jdbc.connection.url.property.replace";
	private static final String JDBC_PATH_PREFIX = "jdbc:derby:";
	
	public String createDatabasePath(){

		String separator = System.getProperty("file.separator");
		String userDir = System.getProperty("user.home"); 
		String dbPath = JDBC_PATH_PREFIX + userDir + separator + "statizo" + separator + "database;create=true";
		return dbPath;

	}

	public DatabaseConfigurator() {

		props = new Properties();

		try {

			props.load(this.getClass().getResourceAsStream(JDBC_PATH));
			
			boolean replaceUrl = Boolean.valueOf(props.getProperty(JDBC_URL_REPLACE_PROPERTY));
			if(replaceUrl){
				String urlPropertyName = props.getProperty(URL_PROPERTY_NAME);
				props.remove(urlPropertyName);
				props.setProperty(urlPropertyName,createDatabasePath());
			}
			

		} catch (IOException e1) {

			throw new NullPointerException(JDBC_PATH + " not found. ");
		}

	}

	public Properties getProperties(){
		return props;
	}

}